<template>
	<view class="calendar-wrapper">
		<view class="header" v-if="headerBar">
			<view class="yearM_box font38" @click="show = true">{{ y + '.' + formatNum(m) }}</view>
			<!-- <image class="triangleImg" @click="show = true" src="https://ebc-prod.cdn.benwunet.com/uni-static/img3.3.0/triangle.png" mode="aspectFill"></image> -->
			<text class="bwfont bw-sanjiao1 triangleImg"></text>
		</view>
		<view class="week">
			<view class="week-day font28" v-for="(item, index) in weekDay" :key="index">{{ item }}</view>
		</view>
		<view :class="{ hide: !monthOpen }" class="content" :style="{ height: height }">
			<view :style="{ top: positionTop + 'rpx' }" class="days">
				<view class="item" v-for="(item, index) in dates" :key="index">
					<view
						class="day"
						@click="selectOne(item, $event)"
						:class="{
							CurM: item.isCurM,
							choose: choose == `${item.year}-${item.month}-${item.date}` && item.isCurM,
							isMarkDay: isMarkDay(item.year, item.month, item.date),
							today: isToday(item.year, item.month, item.date)
						}"
					>
						{{ Number(item.date) }}
					</view>
					<view class="isRound" v-if="isMarkDay(item.year, item.month, item.date)"></view>
				</view>
			</view>
		</view>
		<i @click="toggle" class="bw-zhankai bwfont weektoggle" :class="{ down: monthOpen }"></i>
		<u-datetime-picker
			:show="show"
			@close="show = false"
			@cancel="show = false"
			:closeOnClickOverlay="true"
			confirmColor="#BF8355"
			cancelColor="#111018"
			v-model="selectYM"
			mode="year-month"
			@confirm="confirmDate"
		></u-datetime-picker>
	</view>
</template>

<script>
export default {
	name: 'ren-calendar',
	props: {
		// 星期几为第一天(0为星期日)
		weekstart: {
			type: Number,
			default: 0
		},
		// 标记的日期
		markDays: {
			type: Array,
			default: () => {
				return []; //例如["2023-05-01", "2023-05-03", "2023-04-13"]
			}
		},
		//是否展示月份切换按钮
		headerBar: {
			type: Boolean,
			default: true
		},
		// 是否展开
		open: {
			type: Boolean,
			default: true
		},
		//是否可收缩
		collapsible: {
			type: Boolean,
			default: true
		},
		//未来日期是否不可点击
		disabledAfter: {
			type: Boolean,
			default: true
		}
	},
	data() {
		return {
			weektext: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
			y: new Date().getFullYear(), // 年
			m: new Date().getMonth() + 1, // 月
			dates: [], // 当前月的日期数据
			positionTop: 0,
			monthOpen: true,
			choose: '',
			show: false,
			selectYM: new Date().getFullYear() + '-' + this.formatNum(new Date().getMonth() + 1),
			imgUrl: 'https://ebc-prod.cdn.benwunet.com/uni-static/img3.3.0/top.png',
		};
	},
	created() {
		this.dates = this.monthDay(this.y, this.m);
		!this.open && this.toggle();
	},
	mounted() {
		// this.choose = this.getToday().date;
	},
	computed: {
		// 顶部星期栏
		weekDay() {
			return this.weektext.slice(this.weekstart).concat(this.weektext.slice(0, this.weekstart));
		},
		height() {
			return (this.dates.length / 7) * 92 + 'rpx';
		}
	},
	methods: {
		formatNum(num) {
			let res = Number(num);
			return res < 10 ? '0' + res : res;
		},
		// 确定日期
		confirmDate(data) {
			this.$nextTick(() => {
				this.selectYM = this.formatterDate(data.value);
			});
			this.show = false;
		},

		// 时间戳转换为年月
		formatterDate(timeStamp) {
			const date = new Date(timeStamp); // 创建Date对象
			const year = date.getFullYear(); // 获取年份
			let month = date.getMonth() + 1;
			month = this.formatNum(month);
			this.y = year;
			this.m = month;
			this.dates = this.monthDay(year, month);
			const obj = {
				year: year,
				month: month
			};
			this.$emit('changeMonth', obj);
			return `${year}.${month}`; // 返回格式化后的日期字符串
		},
		getToday() {
			let date = new Date();
			let y = date.getFullYear();
			let m = date.getMonth();
			let d = date.getDate();
			let week = new Date().getDay();
			let weekText = ['日', '一', '二', '三', '四', '五', '六'];
			let formatWeek = '星期' + weekText[week];
			let today = {
				date: y + '-' + this.formatNum(m + 1) + '-' + this.formatNum(d),
				week: formatWeek
			};
			return today;
		},
		// 获取当前月份数据
		monthDay(y, month) {
			let dates = [];
			let m = Number(month);
			let firstDayOfMonth = new Date(y, m - 1, 1).getDay(); // 当月第一天星期几
			let lastDateOfMonth = new Date(y, m, 0).getDate(); // 当月最后一天
			let lastDayOfLastMonth = new Date(y, m - 1, 0).getDate(); // 上一月的最后一天
			let weekstart = this.weekstart == 7 ? 0 : this.weekstart;
			let startDay = (() => {
				// 周初有几天是上个月的
				if (firstDayOfMonth == weekstart) {
					return 0;
				} else if (firstDayOfMonth > weekstart) {
					return firstDayOfMonth - weekstart;
				} else {
					return 7 - weekstart + firstDayOfMonth;
				}
			})();
			let endDay = 7 - ((startDay + lastDateOfMonth) % 7); // 结束还有几天是下个月的
			for (let i = 1; i <= startDay; i++) {
				dates.push({
					date: this.formatNum(lastDayOfLastMonth - startDay + i),
					day: weekstart + i - 1 || 7,
					month: m - 1 >= 0 ? this.formatNum(m - 1) : 12,
					year: m - 1 >= 0 ? y : y - 1
				});
			}
			for (let j = 1; j <= lastDateOfMonth; j++) {
				dates.push({
					date: this.formatNum(j),
					day: (j % 7) + firstDayOfMonth - 1 || 7,
					month: this.formatNum(m),
					year: y,
					isCurM: true //是否当前月份
				});
			}
			for (let k = 1; k <= endDay; k++) {
				dates.push({
					date: this.formatNum(k),
					day: (lastDateOfMonth + startDay + weekstart + k - 1) % 7 || 7,
					month: m + 1 <= 11 ? this.formatNum(m + 1) : 0,
					year: m + 1 <= 11 ? y : y + 1
				});
			}
			return dates;
		},
		isWorkDay(y, m, d) {
			//是否工作日
			let ymd = `${y}/${m}/${d}`;
			let formatDY = new Date(ymd.replace(/-/g, '/'));
			let week = formatDY.getDay();
			if (week == 0 || week == 6) {
				return false;
			} else {
				return true;
			}
		},
		isFutureDay(y, m, d) {
			//是否未来日期
			let ymd = `${y}/${m}/${d}`;
			let formatDY = new Date(ymd.replace(/-/g, '/'));
			let showTime = formatDY.getTime();
			let curTime = new Date().getTime();
			if (showTime > curTime) {
				return true;
			} else {
				return false;
			}
		},
		// 标记日期
		isMarkDay(y, m, d) {
			let flag = false;
			// console.log('传递过来需要标记的日期项', this.markDays);
			this.markDays.find(item => {
				let dy = `${y}-${m}-${d}`;
				if (item == dy) {
					flag = true;
				}
			});
			return flag;
		},
		isToday(y, m, d) {
			let checkD = y + '-' + m + '-' + d;
			let today = this.getToday().date;
			if (checkD == today) {
				return true;
			} else {
				return false;
			}
		},
		// 展开收起
		toggle() {
			this.monthOpen = !this.monthOpen;
			if (this.monthOpen) {
				// 展开
				this.positionTop = 0;
				console.log('1', this.monthOpen);
				this.$emit('changeStatus', this.monthOpen);
			} else {
				// 收起
				console.log('2', this.monthOpen);
				this.$emit('changeStatus', this.monthOpen);
				let index = -1;
				this.dates.forEach((i, x) => {
					this.isToday(i.year, i.month, i.date) && (index = x);
				});
				// this.positionTop = -((Math.ceil((index + 1) / 7) || 1) - 1) * 92;
				this.positionTop = 0;
			}
		},
		// 点击回调
		selectOne(i, event) {
			let date = `${i.year}-${i.month}-${i.date}`;
			// 选择日期的时间戳
			let selectD = new Date(date).getTime();
			// 当天的时间戳
			let curTime = new Date().getTime();
			let week = new Date(date).getDay();
			let weekText = ['日', '一', '二', '三', '四', '五', '六'];
			let formatWeek = '星期' + weekText[week];
			let response = {
				date: date,
				week: formatWeek
			};
			if (!i.isCurM) {
				return false;
			}
			if (!this.isMarkDay(i.year, i.month, i.date)) {
				return false;
			}
			if (this.choose == `${i.year}-${i.month}-${i.date}`) {
				this.choose = '';
			} else {
				this.choose = date;
			}
			response.choose = this.choose;
			// if (selectD > curTime) {
			// 	if (this.disabledAfter) {
			// 		return false;
			// 	} else {
			// 		console.log(11111);
			// 		if(this.choose == `${i.year}-${i.month}-${i.date}`){
			// 			this.choose = ''
			// 		}else{
			// 			this.choose = date;
			// 		}

			// 		this.$emit('onDayClick', response);
			// 	}
			// } else {
			// 	console.log(22222);
			// 	this.choose = date;
			// 	this.$emit('onDayClick', response);
			// }
			this.$emit('selectDate', response);
		},
		//改变年月
		changYearMonth(y, m) {
			this.dates = this.monthDay(y, m);
			this.y = y;
			this.m = m;
		},
		changeMonth(type) {
			if (type == 'pre') {
				this.$emit('toogleMonth', 'pre');
				if (this.m + 1 == 2) {
					this.m = 12;
					this.y = this.y - 1;
				} else {
					this.m = this.m - 1;
				}
			} else {
				this.$emit('toogleMonth', 'next');
				if (this.m + 1 == 13) {
					this.m = 1;
					this.y = this.y + 1;
				} else {
					this.m = this.m + 1;
				}
			}
			this.dates = this.monthDay(this.y, this.m);
			const obj = {
				year: this.y,
				month: this.m
			};
			this.$emit('changeMonth', obj);
		}
	}
};
</script>

<style lang="scss" scoped>
::v-deep .uni-picker-view-mask {
	background: none !important;
}
.calendar-wrapper {
	font-size: 28rpx;
	text-align: center;
	padding-bottom: 10rpx;
	background-color: var(--viewBgColor);
	margin-top: 18rpx;
	border-radius: 8rpx;
	box-shadow: 0rpx 8rpx 20rpx 0rpx rgba(0, 0, 0, 0.2);

	.header {
		display: flex;
		align-items: center;
		padding: 0 22rpx;
		height: 88rpx;
		font-size: 32rpx;
		font-weight: bold;
		.yearM_box {
			color: var(--titleFontColor);
			font-family: PingFang SC-Bold, PingFang SC;
			font-weight: 400;
		}
		.triangleImg {
			color: var(--titleFontColor);
			font-size: 16rpx;
			margin-left: 15rpx;
		}
	}

	.week {
		display: flex;
		align-items: center;
		height: 80rpx;
		line-height: 80rpx;
		view {
			flex: 1;
			color: var(--contentFontDarkColor);
		}
	}

	.content {
		position: relative;
		overflow: hidden;
		transition: height 0.4s ease;

		.days {
			transition: top 0.3s;
			display: flex;
			align-items: center;
			flex-wrap: wrap;
			position: relative;

			.item {
				position: relative;
				display: block;
				height: 94rpx;
				line-height: 94rpx;
				width: calc(100% / 7);
				display: flex;
				flex-direction: column;
				/* justify-content: center; */
				align-items: center;
				.isRound {
					width: 12rpx;
					height: 12rpx;
					border-radius: 50%;
					background-color: #dcaf79;
					margin: 10rpx 0;
				}
				.day {
					font-style: normal;
					display: inline-block;
					vertical-align: middle;
					width: 60rpx;
					height: 60rpx;
					line-height: 60rpx;
					border-radius: 60rpx;
					color: #747986;
					font-size: 32rpx;
					flex-shrink: 0;
					&.CurM {
						color: var(--contentFontLightColor);
					}
					&.isMarkDay {
						background-color: var(--bottomPopupBackTwoColor);
						color: var(--selectedFontColor);
						opacity: 1;
					}

					&.choose {
						background: linear-gradient(360deg, var(--rampButtonBackEndColor) 0%, var(--rampButtonBackStartColor) 100%);
						color: var(--contentBgImageTitleColor);
					}
				}
			}
		}
	}

	.hide {
		height: 92rpx !important;
	}

	.weektoggle {
		color: var(--titleFontColor);
		font-size: 12rpx;
		position: relative;
		display: block;
		padding: 10rpx 0;
		transform: rotate(0deg);
		&.down {
			transform: rotate(180deg);
			bottom: 0;
		}
	}
}
</style>
